<?php

/* 优惠活动关联的商品 activity_goods */
class ActivitygoodsModel extends BaseModel
{
    var $table  = 'activity_goods';
    var $prikey = 'id';
    var $_name  = 'activitygoods';
    var $_relation  = array(
        'belongs_to_activity' => array(
            'model'         => 'activity',
            'type'          => BELONGS_TO,
            'foreign_key'   => 'act_id',
            'reverse'       => 'has_activitygoods',
        ),
        'belongs_to_goods' => array(
            'model'         => 'goods',
            'type'          => BELONGS_TO,
            'foreign_key'   => 'goods_id',
            'reverse'       => 'has_activitygoods',
        ),
    );

    /**
     *   删除活动商品
     */
    function drop($conditions, $fields = 'goods_img')
    {
        import('img_server');
        $droped_rows = parent::drop($conditions, $fields);
        if ($droped_rows)
        {
            restore_error_handler();
            $droped_data = $this->getDroppedData();
            foreach ($droped_data as $key => $value)
            {
                if ($value['goods_img'])
                {
                    $imageUrl = remove_image_server_host($value['goods_img']);
                    @unlink(ROOT_PATH . '/' . $imageUrl);  //删除图片文件
                }
            }
            reset_error_handler();
        }

        return $droped_rows;
    }

    /**
     * 获取参与活动的商品数据
     *
     * @author    yanghj  2015.04.22
     * @param     $goods_ids array 或者 int   商品的ID数组或者商品ID
     *
     */
    function _get_activity_goods($goods_ids = 0)
    {

        $arr = array();
        $conditions = "activity.start_time < ".gmtime()." AND activity.end_time > ".gmtime()." AND goods_id " . db_create_in($goods_ids);
        $activity_goods = $this->find(array(
            'conditions'    => $conditions,
            'fields'    => 'goods_id, promote_discount, promote_price, activity.act_id, activity.act_name, activity.start_time, activity.end_time,activity.discount_type, activity.free_shipping',
            'join'      => 'belongs_to_activity',
        ));
        if($activity_goods)
        {
            foreach($activity_goods as $goods)
            {
                $arr[$goods['goods_id']] = $goods;
            }
        }
        return $arr;
    }
}

?>